AddCSLuaFile('shared.lua');
AddCSLuaFile('cl_init.lua');

include('shared.lua');

function ENT:GetTeam()
	return self.Team;
end

function ENT:Initialize()
	//Setup model
	self.Entity:SetModel("models/props_combine/breenclock.mdl");
	self.Entity:PhysicsInit( SOLID_VPHYSICS );
	self.Entity:SetMoveType( MOVETYPE_VPHYSICS );
	self.Entity:SetSolid( SOLID_VPHYSICS );
	
	local phys = self.Entity:GetPhysicsObject();
	
	if(phys:IsValid()) then
		phys:Wake();
	end
	
	//Create initial variables
	self.blockName = "";
	self.isBuilding = false;
	self.endTime = 0;
	self.startTime = 0;
	self.Team = 0;
end

//Starts the building process
function ENT:StartBuild(name, time, t, tr)
	//Store passed information
	self.blockName = name;
	self.isBuilding = true;
	
	//Record time of start and duration
	self.startTime = CurTime();
	self.endTime = time;
	self.Team = t;
	self.tr = tr;
end

function ENT:Think()
	if(!self.isBuilding) then return; end
	
	//Get elapsed time
	local elapsed = CurTime() - self.startTime;
	
	//If time is up, create entity
	if(elapsed >= self.endTime) then self:Build(); end
end

//Sets the entities position based on size and trace
function SetEntPos(tr, ent)
	ent:SetPos(tr.HitPos - tr.HitNormal * ent:OBBMins().z);
end

//Constructs the entity
function ENT:Build()
	//Set our building to false
	self.isBuilding = false;
	
	//Create and spawn entity
	local ent = ents.Create("bh_block");
	ent:Spawn();
	
	//Set it's position and angles
	ent:SetPos(self:GetPos());
	ent:SetAngles(self:GetAngles());
	ent:SetBlock(self.blockName, self.Team);
	ent.userid = self.userid;
	SetEntPos(self.tr, ent);
	constraint.Weld(ent, self.tr.Entity, self.tr.PhysicsBone, 0, 0);
	
	//Create spawn effect
	local e = EffectData();
	e:SetStart(self:GetPos());
	e:SetOrigin(self:GetPos());
	e:SetEntity(ent);
	util.Effect("propspawn", e);
	
	//Remove self
	self:Remove();
end

function ENT:GetPercent()
	//Returns ratio of elapsed to ending time
	local elapsed = CurTime() - self.startTime;
	return elapsed / self.endTime;
end

//Run when entity is damaged
function ENT:OnTakeDamage(dmg)
	//Find attacker
	local att = dmg:GetAttacker();
	
	//If is player and opposite team
	if(!att:IsPlayer()) then return; end
	if(att:Team() == self.Team) then return; end
	
	//Destroy ourselves
	hook.Call("IncrementBlocks", nil, self.Team, -1);
	self:Remove();
end